﻿using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

using IQToolkit;

namespace LINQToolKit.Collections
{
    /// <summary>
    /// Perform the expression on a IEnumerable collection
    /// </summary>
    public sealed class ExpressionExecutor : ExpressionVisitor
    {
        private IEnumerable _result;

        protected override Expression VisitMethodCall(MethodCallExpression m)
        {
            if (m.Method.DeclaringType == typeof(Queryable) ||
                typeof(IQueryable).IsAssignableFrom(m.Object.GetType()))
            {
                if (m.Arguments[0] is MethodCallExpression)
                {
                    this.Visit(m.Arguments[0]);
                }

                this.ExecuteMethod(m);
            }

            return m;
        }

        private void ExecuteMethod(MethodCallExpression m)
        {
            IList<object> arguments = 
                EnumerableHelper.GetArgumentValues(m.Arguments.Skip(1).ToList());
            arguments.Insert(0, this._result);
            IList<Type> argumentTypes = arguments.Select(arg => arg.GetType()).ToList();
            Type sourceType = this._result.GetType().GetGenericArguments()[0];
            Type resultType = m.Type.GetGenericArguments()[0];
            MethodInfo method = EnumerableHelper.GetMethod(
                m.Method.Name, argumentTypes, sourceType, resultType);

            if (method == null)
            {
                throw new NotImplementedException(m.Method.Name);
            }
            else
            {
                this._result = (IEnumerable)method.Invoke(null, arguments.ToArray<object>());
            }
        }

        public IEnumerable Execute(IEnumerable source, Expression expression)
        {
            this._result = source;
            base.Visit(expression);

            return this._result;
        }
    }
}